/**
 * 
 */
require(['jquery',
         'global',
         'module/util',
         'module/datatables',
         'bootbox.min',
         'module/ajax',
         'jquery.validate',
         'bootstrap',
         'pixeladmin',
         'requirejs/domready!'], 
	function($, global, util, datatables, bootbox){
		window.PixelAdmin.start();
		var mainTable = null;

		var checkTr = function(data,type,full){
	    };

	    var operate = function(data,type,full){
	    	if(full.type == 1) return ""; 
	    	return '<a  class="editOne" href="javascript:void(0)" data-id="'+full.id+'">编辑</a>'+
			 '&nbsp;|&nbsp;<a href="javascript:void(0)" class="deleteOne" data-id="'+full.id+'">删除</a>'+
			 '&nbsp;|&nbsp;<a href="javascript:void(0)" class="detail" data-id="'+full.id+'">查看</a>';
	    };

		var _rendarTable = function(){
			var options = {};
			options.tableId = '#jq-datatables-example';
			options.aaSorting = [[0,"asc"]];
			options.sAjaxSource = global.context+"/web/role/searchbyCon";
			options.functionList = {"checkTr":checkTr,"operate":operate};
	        mainTable = datatables.init(options);
			
			var result = util.getSearchData("#search-area") ;
			mainTable.setParams(result);
			
			$('#jq-datatables-example').css('width', "100%");
			return mainTable.create();
		};
		
		var bindEvent = function(){
			$("#search-btn").on("click",function(){
				mainTable.setParams(util.getSearchData('#search-area'));
				mainTable.invoke("fnDraw");
			});
			$("#search-area").on("keydown",function(e){
				if(e.which == 13){
					$("#adminuser-search-btn").trigger("click");
					return false;
				}
			});
			$('body').on('click', '.deleteOne', function(){//删除确认
				var target = $(this);
				bootbox.confirm({
					buttons: {  
			            confirm: {  
			                label: '确认',  
			                className: 'btn-myStyle'  
			            },  
			            cancel: {  
			                label: '取消',  
			                className: 'btn-default'  
			            }  
		      		 },  
					message: "确认要删除吗?",
					callback: function(isOk) {
						if(isOk){
							$.ajax({
						        'url' : global.context+'/web/role/doDelete/'+target.data('id'),
						        'type' : 'DELETE',
						        'dataType' : 'json',
						        'success' : function(result) {
						        	if(result.code=='ACK'){
						        		mainTable.invoke("fnDraw");// 删除成功后，refresh列表
						        	}
						        },
						        'error' : function() {
						        }
							});
						}
					},
					className: "bootbox-sm"
				});	
			});

			//点击新建按钮时，显示角色窗口
			$('body').on('click', '.newBtn', function(){
				adminUserForm.resetForm();
				$("#roleModal").find("input[type='text'],select").removeClass('highlight-error');
				$("#myform input").val('');
				$(".modal-title").html("添加角色");
				$('#myform').attr("action", global.context+"/web/role/doAdd") ;
				$('#roleModal').modal('show');
			});
			
			//点击编辑时，显示角色窗口
			$('body').on('click', '.editOne', function(){
				adminUserForm.resetForm();
				$(".jquery-validate-error").removeClass('jquery-validate-error');
				$("#roleModal").find("input[type='text'],select").removeClass('highlight-error');
				$(".modal-title").html("编辑角色");
				var me = $(this);
				$('#myform').attr('action', global.context+'/web/role/doEdit/'+me.attr("data-id"));
				var url =  global.context+"/web/role/toEdit/"+ me.attr("data-id");
				$.ajax({
						url:url,
		                type: "GET",
		                dataType: "json",
		                contentType: 'application/json;charset=utf-8',
		                error: function(request) {
		                    $('#alertsDanger').find(".modal-body").text(request.statusText);
							$('#alertsDanger').modal();
		                },
		                success: function(result) {
		                	$("#roleName").val(result.roleName);
		                	$("#roleDesc").val(result.roleDesc);
		                	
		                	$('#roleModal').modal('show');
		                }
		         });
			});
			//查看角色下所有人员信息
			$('body').on('click', '.detail', function(){
				adminUserForm.resetForm();
				$(".modal-title").html("人员信息");
				var me = $(this);
				var url =  global.context+"/web/role/detail/"+ me.attr("data-id");
				$.ajax({
						url:url,
		                type: "GET",
		                dataType: "json",
		                contentType: 'application/json;charset=utf-8',
		                error: function(request) {
		                    $('#alertsDanger').find(".modal-body").text(request.statusText);
							$('#alertsDanger').modal();
		                },
		                success: function(result) {
		                	var container=$("#userContainer");
		                	container.empty();
		                	for(var i=0;i<result.length;i++){
		                		if(result[i]){
		                			container.append('<input  type="text"  style="float: left;" value="'+result[i].useruame+'" /> ');
		                			container.append('<input  type="text"  style="float: left;" value="'+result[i].name+'" /> ');
		                		}
		                	}
		                	$('#roleUser').modal('show');
		                }
		         });
			});
		};
		
		var init = function(){
			_rendarTable();
			bindEvent();
		};
		
		init();
	
		//表单校验加提交
		var adminUserForm = $('#myform').validate({
			onkeyup : false,
			rules:{
				roleName:{
					required: true,
	            	rangelength: [2,30],
	            },
	            roleDesc:{
					required: true,
	            	rangelength: [2,30],
	            }
		    },
		    messages : {
		    	roleName:{
		    		  required: "角色名称不能为空",
		        	  rangelength : $.format("姓名长度：{0}-{1}个字符")
		        },
		        roleDesc:{
		    		  required: "角色描述不能为空",
		        	  rangelength : $.format("姓名长度：{0}-{1}个字符")
		        }
		    },
			submitHandler: function(form) {
				util.ajax_submit(form).complete(function(xhr) {
					var result = $.parseJSON(xhr.responseText);
					if(result.code=="ACK"){
						mainTable.invoke("fnStandingRedraw");//refresh表格
						$("#roleModal").modal('hide');
						$("#roleModal input[type='text']").val('');
					}
				});
		    },
		    errorPlacement:function(error, element){//自定义错误提示放置的位置
		    	var $errorPanel = '<div class="validate-error-panel"></div>';
		    	element.closest(".info_item").after($errorPanel);
		    	error.appendTo(element.closest(".info_item").next('.validate-error-panel'));
		    },
		    highlight: function(element, errorClass) {  
		    	$(element).addClass('highlight-error');//未通过验证的元素高亮
	        },
	        unhighlight: function(element, errorClass) {  
		    	$(element).removeClass('highlight-error');//通过验证去掉高亮
	        },
	        success: function(label) {  
	        }  
		});
		
		//关闭modal框
		$("#roleModal").on('click','.close',function(){
			adminUserForm.resetForm();
			$("#roleModal").find("input[type='text'],select").removeClass('highlight-error');
		});
});